package trafficAgent;

import java.util.ArrayList;

import model.Car;
import jade.core.behaviours.OneShotBehaviour;

public class MoveCars extends OneShotBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	TrafficAgent agent; 
	
	public MoveCars(final TrafficAgent myAgent) {
		super(myAgent);
		agent = myAgent;
	}
	
	@Override
	public void action() {
		
		ArrayList<Car> cars = new ArrayList<Car>();
		for(Car c: agent.getMap().getCars())
			if(!c.isMoved())
				cars.add(c);
		boolean moved = true;
		while(moved){
			moved = false;
			ArrayList<Car> toRemove = new ArrayList<Car>();
			for(final Car c: cars){
				if(!c.isAtCrossRoad()){
					if(agent.getMap().freeRoad(c.getCurPos(), c.getCurPosIndex()+1)){
						c.moveForward();
						toRemove.add(c);
						moved = true;
					}
				}
			}
			cars.removeAll(toRemove);
			
		}
			
		
		agent.addBehaviour(new MasterBehaviour(agent));

	}

}
